// pages/chatAi/chatAi.js
const app = getApp()

Page({
  data: {
    messages: [],        // 聊天消息列表
    inputMessage: '',    // 输入框内容
    isLoading: false,    // 是否正在加载
    scrollTop: 0,        // 滚动位置
    defaultAvatar: '/images/default-avatar.png', // 默认头像
    userInfo: null,      // 用户信息
  },

  onLoad: function (options) {
    this.initUserInfo();
  },

  onReady: function () {
    // 页面渲染
  },

  onShow: function () {
    // 页面显示
  },

  onHide: function () {
    // 页面隐藏
  },

  onUnload: function () {
    // 页面卸载
  },

  
  //初始化用户信息
  
  initUserInfo: function() {
    const userInfo = app.globalData.userInfo;
    if (userInfo) {
      this.setData({
        userInfo: userInfo
      });
    } else {
      // 如果没有用户信息，尝试获取
      this.getUserInfo();
    }
  },

  
  //获取用户信息
  
  getUserInfo: function() {
    const that = this;
    wx.getStorage({
      key: 'userInfo',
      success: function(res) {
        that.setData({
          userInfo: res.data
        });
        app.globalData.userInfo = res.data;
      }
    });
  },

  
  //输入框输入事件
  
  onInput: function(e) {
    this.setData({
      inputMessage: e.detail.value
    });
  },

  
  // 滚动事件
  
  onScroll: function(e) {
    // 可以在这里处理滚动逻辑
  },

  
  //发送消息
  
  sendMessage: function() {
    const message = this.data.inputMessage.trim();
    if (!message || this.data.isLoading) return;

    // 添加用户消息到列表
    const userMessage = {
      sender: 'user',
      content: message,
      avatarUrl: this.data.userInfo ? this.data.userInfo.avatarUrl : this.data.defaultAvatar
    };

    this.setData({
      messages: [...this.data.messages, userMessage],
      inputMessage: ''
    });

    // 设置加载状态
    this.setData({ isLoading: true });

    // 滚动到底部
    this.scrollToBottom();

    // 添加AI正在输入状态
    const aiMessage = {
      sender: 'ai',
      content: '',
      loading: true
    };

    this.setData({
      messages: [...this.data.messages, aiMessage]
    });

    // 调用后端API
    this.callAIBackend(message);
  },

  
  //调用AI后端接口
   
  callAIBackend: function(message) {
    const that = this;
    const userId = this.getUserId();

    wx.request({
      url: 'http://localhost:8080/chatai/message2',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token') || ''
      },
      data: {
        message: message,
        userId: userId
      },
      success: function(res) {
        console.log('后端返回完整数据:', res.data);
        if (res.data.code === 200) {
          that.updateAIMessage(res.data.data);
        } else {
          console.error('后端返回错误：code=' + res.data.code + ', msg=' + res.data.msg);
          that.showError('获取AI回复失败: ' + (res.data.msg || '未知错误'));
        }
      },
      fail: function(error) {
        console.error('发送消息失败:', error);
        that.showError('网络请求失败，请检查网络连接');
      },
      complete: function() {
        that.setData({ isLoading: false });
        that.scrollToBottom();
      }
    });
  },

 
  //更新AI消息
  
  updateAIMessage: function(content) {
    const messages = this.data.messages.map((msg, index) => {
      if (index === this.data.messages.length - 1 && msg.sender === 'ai' && msg.loading) {
        return {
          sender: 'ai',
          content: content,
          loading: false
        };
      }
      return msg;
    });

    this.setData({ messages });
  },

  
  //显示错误消息
  
  showError: function(errorMsg) {
    const messages = this.data.messages.map((msg, index) => {
      if (index === this.data.messages.length - 1 && msg.sender === 'ai' && msg.loading) {
        return {
          sender: 'ai',
          content: '抱歉，我暂时无法回应你的请求：' + errorMsg,
          loading: false
        };
      }
      return msg;
    });

    this.setData({ messages });
  },

 
  //滚动到底部
   
  scrollToBottom: function() {
    setTimeout(() => {
      this.setData({
        scrollTop: 99999
      });
    }, 100);
  },

 
   // 清空聊天记录
  
  clearChat: function() {
    const that = this;
    wx.showModal({
      title: '提示',
      content: '确定要清空聊天记录吗？',
      success: function(res) {
        if (res.confirm) {
          that.setData({
            messages: []
          });
        }
      }
    });
  },

  getUserId: function() {
    // 从全局数据或缓存中获取用户ID
    if (this.data.userInfo && this.data.userInfo.userId) {
      return this.data.userInfo.userId;
    }
    
    const userId = wx.getStorageSync('userId');
    if (userId) {
      return userId;
    }
    
    return '14f25502-378d-46e5-a40c-b16592811319';
  },


  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },


  onReachBottom: function () {
    
  },

  onShareAppMessage: function () {
    return {
      title: 'AI智能助手',
      path: '/pages/chatAi/chatAi'
    }
  }
})